package DBLayer;

import java.sql.*;

public class DBConnection {
	private static final String driver = "jdbc:sqlserver://balder.ucn.dk:1433";
	private static final String databaseName = ";databaseName=dmai0913_1";
	private static final String userName = ";user=dmai0913_1";
	private static final String password = ";password=strictPassword";

	private static Connection con;

	private static DBConnection instance = null;

	private DBConnection() {
		String url = driver + databaseName + userName + password;

		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (Exception e) {
			System.out.println("Can not find the driver" + e.getMessage());
		}

		try {
			con = DriverManager.getConnection(url);
			con.setAutoCommit(true);
		} catch (Exception e) {
			System.out.println("Problems with the connection to the database"
					+ e.getMessage());
		}
	}

	public static void closeConnection() {
		try {
			con.close();
		} catch (Exception e) {
			System.out.println("Error trying to close the database "
					+ e.getMessage());
		}
	}

	public Connection getDBcon() {
		return con;
	}

	public static DBConnection getInstance() {
		if (instance == null)
			instance = new DBConnection();

		return instance;
	}

	public static void startTransaction() {
		try {
			con.setAutoCommit(false);
		} catch (Exception e) {
			System.out.println("fail start transaction"+e.getMessage());
		}
	}

	public static void commitTransaction() {
		try {
			con.setAutoCommit(true);
		} catch (Exception e) {
			System.out.println("fail commit transaction"+e.getMessage());
		}
	}

	public static void rollbackTransaction() {
		try {
			con.rollback();
			con.setAutoCommit(true);
		} catch (Exception e) {
			System.out.println("fail rollback transaction"+e.getMessage());
		}
	}
}
